<template>
  <div class="my-upload">
    <el-upload
      :accept="accept"
      class="el-upload-wrap"
      :id="'el-upload' + count"
      :action="$upLoad"
      :class="fileList.length < limit ? '' : 'my'"
      :limit="limit"
      :show-file-list="true"
      :file-list="fileList"
      :ref="'el-upload' + count"
      :list-type="listType"
      :auto-upload="autoUpload"
      :before-upload="beforeUpload"
      :multiple="multiple"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-progress="handleProcess"
      :disabled="disabled"
    >
      <template v-if="mode == 'cropper'">
        <!-- <img
          :src="fileList[0].url"
          alt=""
          srcset=""
          v-if="fileList.length > 0"
        /> -->
        <template v-if="uploaderIconIsImage && fileTempList.length == 0">
          <img
            :src="uploaderIcon"
            alt=""
            :style="[uploaderIconStyle]"
            class="avatar-uploader-icon"
          />
        </template>
        <template v-if="!uploaderIconIsImage && fileTempList.length == 0"
          ><i class="avatar-uploader-icon" :class="uploaderIcon"></i
        ></template>
      </template>
      <template v-if="mode != 'cropper'">
        <template v-if="uploaderIconIsImage">
          <img
            :src="uploaderIcon"
            alt=""
            :style="[uploaderIconStyle]"
            class="avatar-uploader-icon"
          />
        </template>
        <template v-if="!uploaderIconIsImage"
          ><i class="avatar-uploader-icon" :class="uploaderIcon"></i
        ></template>
      </template>

      <span slot="tip" style="color: #333"></span>
      <template slot="file" slot-scope="{ file }" v-if="mode != 'default'">
        <template v-if="file.fileType == 'image'">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardUpload(file, 'el-upload' + count)"
              v-if="operateType.includes('upload')"
            >
              <i class="el-icon-upload2"></i>
            </span>

            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file, 'el-upload' + count)"
              v-if="operateType.includes('view')"
            >
              <i class="el-icon-zoom-in"></i>
            </span>
            <span
              v-if="!disabled && operateType.includes('down')"
              class="el-upload-list__item-delete"
              @click="handleDownload(file, 'el-upload' + count)"
            >
              <i class="el-icon-download"></i>
            </span>
            <span
              v-if="!disabled && operateType.includes('del')"
              class="el-upload-list__item-delete"
              @click="handleRemove(file, 'el-upload' + count)"
            >
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </template>
        <template v-if="file.fileType == 'video'">
          <video
            :ref="'video' + count"
            :id="'video' + count"
            :src="file.url"
            class="el-upload-list__item-thumbnail"
            style="height: 150px; width: 150px"
            controls="controls"
          >
            您的浏览器不支持视频播放
          </video>

          <span class="el-upload-list__item-actions">
            <span
              v-if="operateType.includes('view')"
              class="el-upload-list__item-preview"
              @click="handleVideoPreview(file, 'video' + count)"
            >
              <i class="el-icon-full-screen"></i>
            </span>
            <span
              v-if="!disabled && operateType.includes('del')"
              class="el-upload-list__item-delete"
              @click="handleRemove(file, 'el-upload' + count)"
            >
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </template>
        <el-progress
          v-if="file2Percentage[file.uid] && file2Percentage[file.uid] != 101"
          type="circle"
          :percentage="file2Percentage[file.uid]"
        ></el-progress>
      </template>
    </el-upload>
    <el-dialog
      title="图片"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      :show-close="false"
    >
      <div style="width: 100%; height: 400px">
        <vue-cropper
          autoCrop
          :fixedBox="option.fixedBox"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          :img="showImg"
          ref="cropper"
          centerBox
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import mix from "./mix.js";
import croperMix from "./croperMix.js";
import fileInfo from "./utils";
import fileTypeSuffix from "./mediaVariables";
var count = 10086;
export default {
  mixins: [mix, croperMix],
  props: {
    // 文件
    myfile: {
      type: String,
    },
    // default | custom | cropper
    mode: {
      type: String,
      default: "custom",
    },
    // 自定义图标 | 图片
    uploaderIcon: {
      type: String,
      default: "el-icon-plus",
    },
    // 自定义图标 | 图片的样式
    uploaderIconStyle: {
      type: Object,
      default() {
        return {
          position: "absolute",
          left: 0,
          top: 0,
          width: "100%",
          height: "100%",
        };
      },
    },
    // 上传文件类型
    acceptType: {
      type: String,
      default: "",
    },
    // 限制数量
    limit: {
      type: Number,
      default: 3,
    },
    // 限制大小
    maxSize: {
      type: Number,
      default: 5, //5M
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      count: ++count, // upload计数ID
      listType: "picture-card",
      file2Percentage: {}, // 文件对应上传进度
      fileList: [],
      fileTempList: [],
      accept: "",
      multiple: true,
      autoUpload: true, // 是否自动上传
      operateType: ["view", "del"],
      // "down",

      $upLoad: "https://www.bangbangtongcheng.com/conven/ht/attach/qnUpload",
      imgUrl: "",
    };
  },
  computed: {
    uploaderIconIsImage() {
      if (/data:image\/|http/.test(this.uploaderIcon)) {
        return true;
      } else {
        return false;
      }
    },
  },
  watch: {
    fileTempList(newV, oldV) {
      if (newV) {
        this.$emit(
          "update:myfile",
          newV.map((item) => item.mediaUrl).join("|") || ""
        );
      }
    },
    fileList(newV, oldV) {
      console.log("fileListfileList 改变了被监听到了");
      this.fileTempList = this.deepClone(this.fileList);
    },
    myfile: {
      handler(newV, oldV) {
        // console.log("newVnewVnewV");
        if (newV && !this.firstLoading) {
          this.fileList = newV.split("|").map((item, index) => {
            return {
              url: this.imgUrl + item,
              uid: +new Date() + index * 108,
              name: item.substring(item.lastIndexOf("/") + 1),
              fileType: this.acceptType || fileInfo.fileType(item),
              mediaUrl: item,
            };
          });
          this.init();
        }
        this.firstLoading = true;
      },
      // immediate: true,
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      console.log(fileInfo.fileType("123.pnG"));
      // 裁剪
      if (this.mode == "cropper") {
        this.autoUpload = false;
        this.multiple = false;
        // this.operateType = this.operateStr
        //   ? this.operateStr.split(",")
        //   : ["view", "down", "del", "upload"];
        this.fileList = this.fileList.slice(0, 1);
      } else if (this.mode == "custom") {
        this.autoUpload = true;
        this.multiple = false;
        this.operateType = this.$attrs.operateType
          ? this.$attrs.operateType.split(",")
          : ["view", "down", "del"];
        this.fileList = this.fileList.slice(0, +this.limit);
      }
      // 上传文件类型限制
      if (this.acceptType) {
        this.accept =
          (fileTypeSuffix[this.acceptType] &&
            fileTypeSuffix[this.acceptType].join(",")) ||
          "";
      }
    },

    // 上传文件之前的钩子
    beforeUpload(file) {
      console.log("beforeUpload", file);
      console.log("beforeUpload", fileInfo.fileType(file));
      // 限制文件大小
      if (this.maxSize && file.size / (1024 * 1024) > this.maxSize) {
        this.$message.warning(`当前限制文件大小不能大于${this.maxSize}M`);
        return false;
      }
      // 传输类型
      if (this.accept) {
        //不赋值就不做限制
        if (this.acceptType != fileInfo.fileType(file)) {
          this.$message({
            message: "文件格式错误",
            type: "error",
            duration: 2000,
          });
          return false;
        }
      }
      //   console.log(file);
      return true;
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      console.log("handleExceed=>当前选择的多或者单文件", files);
      console.log("handleExceed=>已经存在的文件列表", fileList);

      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${fileList.length + files.length} 个文件`
      );
    },
    // 文件上传成功时的钩子
    handleSuccess(response, file, fileList) {
      // console.log("handleSuccess", response);
      console.log("handleSuccess", response, file, fileList);
      file.fileType = fileInfo.fileType(file);
      // file.mediaUrl = response.data[0].url;

      // this.fileList.push(file,file)

      this.fileList.push({
        fileType: fileInfo.fileType(file),
        url: file.url,
        uid: file.uid,
        name: file.name,
        mediaUrl: response.data[0].url,
      });
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, ref) {
      let uploadFiles = this.$refs["el-upload" + this.count].uploadFiles;
      // 手动删除的时候需要
      if (uploadFiles.indexOf(file) > -1) {
        uploadFiles.splice(uploadFiles.indexOf(file), 1);
      }
      // 如果存在就
      var i = this.fileList.findIndex((item) => item.uid == file.uid);
      if (i > -1) {
        this.fileList.splice(i, 1);
      }
      // 如果存在就
      // var i = this.fileTempList.findIndex((item) => item.uid == file.uid);
      // if (i > -1) {
      //   this.fileTempList.splice(i, 1);
      // }

      // uploadFiles.splice(uploadFiles.indexOf(file), 1);

      // this.fileList.splice(this.fileList.indexOf(file), 1);
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      console.log("handleChangehandleChangehandleChange", fileList);
      console.log("handleChangehandleChangehandleChange", this.fileList);

      if (file.percentage == 100) {
        this.file2Percentage[file.uid] = 101;
        setTimeout(() => {
          if (this.fileList.every((item) => item.uid != file.uid)) {
            // this.fileList.push(file);
          }

          // this.deepCopyFileList()
          // this.handleArr(fileList);
          // console.log(
          //   "objectobjectobjectobject",
          //   JSON.stringify(fileList, null, 2)

          // );
          console.log(this.fileList);
        });
      }
      // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
      if (file.percentage == 0) {
        // this.fileUid2Type[file.uid]= fileInfo.fileType(file)
        // console.log(this.fileUid2Type);

        this.file2Percentage = {
          ...this.file2Percentage,
          [file.uid]: 0,
        };
        console.log(this.file2Percentage);
      }

      // 如果是裁剪
      if (this.mode == "cropper") {
        this.prepare(file);
        return false;
      }
    },
    // 文件上传时的钩子
    handleProcess(event, file, fileList) {
      let _self = this;
      if (event.lengthComputable) {
        let val = ((event.loaded / event.total) * 100).toFixed(0);
        var progress = parseInt(val);
        _self.file2Percentage[file.uid] = progress;
        // console.log(_self.file2Percentage[file.uid]);
      }
    },
    // deepCopyFileList(){
    //   this.fileList =JSON.parse(JSON.stringify(this.$refs['el-upload'+this.count].uploadFiles))
    // },
    deepClone(obj) {
      let result = typeof obj.splice === "function" ? [] : {};
      if (obj && typeof obj === "object") {
        for (let key in obj) {
          if (obj[key] && typeof obj[key] === "object") {
            result[key] = this.deepClone(obj[key]); //如果对象的属性值为object的时候，递归调用deepClone,即在吧某个值对象复制一份到新的对象的对应值中。
          } else {
            result[key] = obj[key]; //如果对象的属性值不为object的时候，直接复制参数对象的每一个键值到新的对象对应的键值对中。
          }
        }
        return result;
      }
      return obj;
    },
    printObj(obj) {
      console.log(JSON.stringify(obj, null, 2));
    },
  },
};
</script>

<style lang="less" scoped>
.my-upload {
  // display: inline-block;
  // text-align: center;
  // outline: 0;
  // width: 100%;
  // height: 100%;
  // 默认样式影响了这个，只能再次覆盖
  /deep/ input[type="file"] {
    display: none;
  }

  // 自定义默认图片需要它
  /deep/ .el-upload {
    position: relative;
    overflow: hidden;
  }

  // 如果数量达到限制就让上传框none
  .my {
    /deep/ .el-upload {
      display: none;
    }
  }
}
</style>
